<template>
  <view class="order-detail">
    <view class="form-content">
      <orderForm ref="orderForm" v-if="initFinish" :form-value="formData" :work-id="workId" :form-list="formList" :detail-list="detailList"
                 :rules="rules" :img-show="orderStatus < 2" edit-able able-upload />
    </view>
    <view class="btn-content" v-if="initFinish">
      <button :disabled="!ableSubmit" @click="submit" class="login-btn cu-btn block bg-blue lg">提交</button>
    </view>
    <SubmitSign v-if="signShow" @close="signShow = false" @submit="signSubmit" />
  </view>
</template>

<script>
  import {
    getToken,
  } from '@/utils/auth';
  import orderForm from '../../../common/order-form/orderForm.vue';
  import {
    getOrderDetail,
    getUploadImgUrl,
    commitOrder,
    completeOffice,
  } from '../../../../api/device/device.js';
  import mixins from '../mixins';
  import {
    showConfirm,
  } from '@/utils/common';
  import SubmitSign from '../../../../components/order-detail/SubmitSign';
  
  const formList = [ {
    name: '设备名称',
    code: 'eqName',
    disable: true,
  },
    {
      name: '备注说明',
      code: 'workReceiveRemark',
      type: 'textarea',
      required: true,
    },
  ];
  
  export default {
    components: {
      orderForm,
      SubmitSign,
    },
    mixins: [ mixins ],
    data() {
      return {
        workId: '',
        formData: {},
        initFinish: false,
        ableSubmit: true,
        orderStatus: 1,
        formList,
        rules: {
          workReceiveRemark: {
            rules: [ {
              required: true,
              errorMessage: '请填写备注说明',
            } ],
          },
        },
        signShow: false,
        submitForm: {},
      };
    },
    created() {
    },
    methods: {
      async getData() {
        const res = await getOrderDetail({
          workId: this.workId,
        }).catch(() => {
        });
        if (res.code === 200) {
          this.formData = res.data;
        }
        this.initFinish = true;
      },
      async submit() {
        const {
          workId,
          orderStatus,
        } = this;
        const orderForm = this.$refs.orderForm[ 0 ] || this.$refs.orderForm;
        const {
          formData,
          isSuccess,
        } = await orderForm.getFormData();
        if (!isSuccess) {
          return;
        }
        formData.workId = workId;
        this.submitForm = formData;
        if (orderStatus > 1) {
          this.signShow = true;
          return;
        }
        const {
          fileList,
        } = orderForm.getFileList();
        if (fileList.length < 1) {
          uni.showToast({
            title: '请上传图片',
            icon: 'error',
          });
          return;
        }
        this.ableSubmit = false;
        this.uploadImg(fileList, (resList) => {
          let isSuccess = true;
          resList.forEach((val) => {
            if (val.code !== 200) {
              isSuccess = false;
            }
          });
          this.ableSubmit = true;
          if (isSuccess) {
            this.commitOrder(formData);
          }
        });
      },
      async orderComplete(formData) {
        const confirm = await showConfirm('确定验收合格？').catch(() => {
        });
        if (!confirm.confirm) {
          return;
        }
        
        this.ableSubmit = false;
        const res = await completeOffice(formData).catch(() => {
          this.ableSubmit = true;
        });
        if (res && res.code === 200) {
          uni.showToast({
            title: '提交成功',
            icon: 'success',
          });
          setTimeout(() => {
            this.ableSubmit = true;
            uni.navigateBack({
              delta: 1,
            });
          }, 2000);
          return;
        }
        this.ableSubmit = true;
        uni.showToast({
          title: res.msg || '提交失败',
          icon: 'error',
        });
      },
      async commitOrder(formData) {
        this.ableSubmit = false;
        const res = await commitOrder(formData).catch(() => {
          this.ableSubmit = true;
        });
        if (res && res.code === 200) {
          uni.showToast({
            title: '提交成功',
            icon: 'success',
          });
          setTimeout(() => {
            this.ableSubmit = true;
            uni.navigateBack({
              delta: 1,
            });
          }, 2000);
          return;
        }
        this.ableSubmit = true;
        uni.showToast({
          title: res.msg || '提交失败',
          icon: 'error',
        });
      },
      uploadImg(fileList, callback, photoType = 1) {
        const {
          workId,
        } = this;
        const resultList = [];
        let num = 0;
        fileList.forEach((val, index) => {
          uni.uploadFile({
            url: getUploadImgUrl(),
            name: 'imagefile',
            file: val,
            header: {
              Authorization: `Bearer ${getToken()}`,
            },
            formData: {
              workId,
              photoType,
            },
            complete(res) {
              num += 1;
              resultList[ index ] = JSON.parse(res.data);
              if (num === fileList.length) {
                callback(resultList);
              }
            },
          });
        });
      },
      signSubmit({ file }) {
        const formData = this.submitForm;
        this.uploadImg([ file ], () => {
          this.orderComplete(formData);
        }, 2);
      },
    },
    // onShow() {
    //   const pageList = getCurrentPages();
    //   const param = pageList[ pageList.length - 1 ].options || {};
    // },
    onLoad(e) {
      this.workId = e.workId;
      this.orderStatus = e.status * 1;
      this.getData();
    },
  };
</script>

<style lang="scss" scoped>
  .order-detail {
    
    &, * {
      box-sizing: border-box;
    }
    
    height: 100vh;
    background-color: white;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    
    .form-content {
      flex: 1;
      padding: 10px;
      overflow: auto;
    }
    
    .btn-content {
      padding: 10px;
    }
  }
</style>
